package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Resource
    AttrAttrgroupRelationDao relationDao;
    @Resource
    AttrGroupDao attrGroupDao;
    @Resource
    CategoryDao categoryDao;

    @Resource
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        //保存基本数据
        this.save(attrEntity);
        //保存关联关系   当获取的基本属性才进行保存关联表信息
        if(attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationDao.insert(relationEntity);
        }


    }

    @Override
    public PageUtils queryBaseAttrPase(Map<String, Object> params, Long catelogId, String type) {
        String key = (String)params.get("key");
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type","base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if (!StringUtils.isEmpty(key)){
            wrapper.and((obj)->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        if (catelogId == 0){
            IPage<AttrEntity> page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    wrapper);
            PageUtils pageUtils = new PageUtils(page);
            List<AttrEntity> records = page.getRecords();

            List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
                AttrRespVo attrRespVo = new AttrRespVo();
                BeanUtils.copyProperties(attrEntity, attrRespVo);
                //设置分类和分组的名字
                if("base".equalsIgnoreCase(type)){
                    QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("attr_id", attrEntity.getAttrId());
                    AttrAttrgroupRelationEntity attrId = relationDao.selectOne(queryWrapper);
                    if (attrId != null && attrId.getAttrGroupId()!=null) {
                        Long attrGroupId = attrId.getAttrGroupId();
                        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }

                //设置分类的id
                CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
                if (categoryEntity != null) {
                    attrRespVo.setCatelogName(categoryEntity.getName());
                }

                return attrRespVo;
            }).collect(Collectors.toList());
            pageUtils.setList(respVos);
            return pageUtils;
            //return new PageUtils(page);
        }else{
            wrapper.eq("catelog_id",catelogId);
            IPage<AttrEntity> page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    wrapper);
            PageUtils pageUtils = new PageUtils(page);
            List<AttrEntity> records = page.getRecords();

            List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
                AttrRespVo attrRespVo = new AttrRespVo();
                BeanUtils.copyProperties(attrEntity, attrRespVo);
                //设置分类和分组的名字
                if ("base".equalsIgnoreCase(type)){
                    QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("attr_id", attrEntity.getAttrId());
                    AttrAttrgroupRelationEntity attrId = relationDao.selectOne(queryWrapper);
                    if (attrId != null && attrId.getAttrGroupId()!=null) {
                        Long attrGroupId = attrId.getAttrGroupId();
                        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
                //设置分类的id
                CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
                if (categoryEntity != null) {
                    attrRespVo.setCatelogName(categoryEntity.getName());
                }

                return attrRespVo;
            }).collect(Collectors.toList());
            pageUtils.setList(respVos);
            return pageUtils;
        }
    }

    /**
     * 查询属性详情  ---规格参数，修改
     * @param attrId
     * @return
     */
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //获取分组信息
            QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("attr_id", attrId);
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(queryWrapper);
            if (relationEntity!=null){
                Long attrGroupId = relationEntity.getAttrGroupId();
                attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                if(attrGroupEntity!=null){
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //获取分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrRespVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryService.getById(catelogId);
        if(categoryEntity!=null){
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }

    //更新属性
    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        //修改分组关联 pms_attr_attrgroup_relation   基本属性才有分组
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());


            QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("attr_id",attr.getAttrId());
            Integer count = relationDao.selectCount(queryWrapper);
            if (count>0){
                UpdateWrapper<AttrAttrgroupRelationEntity> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("attr_id",attr.getAttrId());
                relationDao.update(relationEntity,updateWrapper);
            }else{
                relationDao.insert(relationEntity);
            }
        }



    }

    //根据分组id获取相关关联的属性值
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_group_id",attrgroupId);
        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(queryWrapper);
        //收集所有的属性id
        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        //通过获取的属性id集合，查询属性值 进行非空判断
        if (attrIds == null || attrIds.size() ==0){
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }

    //删除属性与分组的关联关系
    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {

        //获取属性关联表中的集合
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        relationDao.deleteBatchRelation(entities);
    }

    /**
     * 获取属性分组没有关联的其他属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1、当前分组只能关联自己所属的分类里面的的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2、当前分组只能关联别的分组没有引用的属性
        //2.1、当前分类下的其他分组
        QueryWrapper<AttrGroupEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("catelog_id",catelogId);
        //queryWrapper.ne("attr_group_id",attrgroupId);
        List<AttrGroupEntity> group = attrGroupDao.selectList(queryWrapper);
        List<Long> collect = group.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //2.2、这些分组关联的属性
        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
        wrapper.in("attr_group_id",collect);
        List<AttrAttrgroupRelationEntity> groupId = relationDao.selectList(wrapper);
        //获取所有的关联属性的ID
        List<Long> attrIds = groupId.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //2.3、从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("catelog_id",catelogId);
        wrapper1.eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (attrIds!=null && attrIds.size()>0){
            wrapper1.notIn("attr_id",attrIds);
        }
        //List<AttrEntity> attrEntities = this.baseMapper.selectList(wrapper1);
        //添加条件查询
        String key = (String)params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper1.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper1);

        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

}